package JavaServlet.TimeServlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/lastAccessTime")
public class TimeServlet extends HttpServlet{
	
		public TimeServlet() {
			System.out.println("TimeServlet.TimeServlet()");
		}
		@Override
		public void init(ServletConfig config) throws ServletException {
		super.init(config);
		String maxOnLine = config.getInitParameter("maxOnLine");
		System.out.println("maxOnLine:" + maxOnLine);
		}
		
		@Override
		protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
			ServletConfig servletConfig = getServletConfig();
			String maxOnLine = servletConfig.getInitParameter("maxOnLine");
			System.out.println("maxOnLine:" + maxOnLine);
			
			ServletContext servletContext = getServletContext();
			String pageSize = servletContext.getInitParameter("pageSize");
			System.out.println("pageSize:" + pageSize);
			resp.setContentType("text/html");
			// 1. 记录当前访问时间，保存到Cookie,不管是不是第一次
			Date date = new Date();
			//System.out.println(date);
			// Fri Aug 23 11:06:54 CST 2019   "yyyy-MM-dd hh:mm:ss"
			// 2019-08-23 11:08:23
			SimpleDateFormat simpleDateFormat = 
					new SimpleDateFormat("yyyy-MM-ddhh:mm:ss");
			String nowTime = simpleDateFormat.format(date);
			Cookie cookie = new Cookie("lastAccessTime", nowTime);
			resp.addCookie(cookie);
			
			// 2.如果不是第一次，可以拿到请求过来的Cookie里面的lastAccessTime
			Cookie[] cookies = req.getCookies();
			String lastAccessTime = null;
			if (cookie != null) {
				for (Cookie coo : cookies) {
					if ("lastAccessTime".equals(coo.getName())) {
						lastAccessTime = coo.getValue();
						System.out.println(lastAccessTime);
					}
				}
			}
			// 3.页面中展示
			// 返回给浏览器
			resp.setContentType("text/html;charset=utf-8");
			PrintWriter printWriter = resp.getWriter();
			if(lastAccessTime == null) {
				printWriter.write("您是第一次访问");
			}else {
				printWriter.write("您上次访问的时间是：" + lastAccessTime);
			}
			printWriter.close();
		}
}
